package org.lagou.sqlSeesion;

import org.lagou.config.BoundSql;
import org.lagou.pojo.Configuration;
import org.lagou.pojo.MapperStatement;
import org.lagou.utils.GenericTokenParser;
import org.lagou.utils.ParameterMapping;
import org.lagou.utils.ParameterMappingTokenHandler;

import java.beans.Expression;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class simpleExecutor implements Executor {

    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {

        PreparedStatement preparedStatement = prepareSql(configuration, mapperStatement, params);

        // 5. 执行sql
        System.out.println("到数据库中查询数据");
        ResultSet resultSet = preparedStatement.executeQuery();

        // 6. 封装返回结果集
        String resultType = mapperStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        ArrayList<Object> objects = new ArrayList<>();

        while (resultSet.next()) {
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            // 查询结果总列数，从1开始算
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);
                //  使用内省 根据数据库表和实体的对应关系 完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            objects.add(o);
        }

        return (List<E>) objects;
    }

    @Override
    public int doUpdate(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {

        PreparedStatement preparedStatement = prepareSql(configuration, mapperStatement, params);

        // 5. 执行sql
        int result = preparedStatement.executeUpdate();
        return result;

    }

    private PreparedStatement prepareSql(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {

        // 1. 注册驱动, 获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取 sql 语句
        String sql = mapperStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3. 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4. 设置参数
        String paramType = mapperStatement.getParamType();
        Class<?> parameterTypeClass = getClassType(paramType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 反射
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1, o);
        }

        return preparedStatement;

    }

    private Class<?> getClassType(String paramType) throws ClassNotFoundException {
        if(paramType != null) {
            Class<?> aClass = Class.forName(paramType);
            return aClass;
        }
        return null;
    }

    // 解析sql 中 #{} ${}, 并提取其中的字段名
    private BoundSql getBoundSql(String sql) {

        // 标记处理类: 配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        // 解析后的sql
        String parseSql = genericTokenParser.parse(sql);
        // 解析后的字段名
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;

    }


}
